package com.group10.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.group10.entity.PageBean;
import com.group10.entity.Result;
import com.group10.entity.User;
import com.group10.entity.UserState;
import com.group10.mapper.AdminMapper;
import com.group10.mapper.UserMapper;
import com.group10.service.UserService;
import com.group10.util.Encrypt;
import com.group10.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.*;

import static com.group10.util.TimeUtil.getFutureTimeAfterNMinutes;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ValidationServiceImpl validationService;
//    @Autowired
//    private UserInfoServiceImpl userInfoService;
    @Autowired
    private AdminMapper adminMapper;

//    通过id查找用户

    @Override
    public User findById(String id) {
        return userMapper.findById(id);
    }

    /*
     * 验证用户的账号状态*/
    @Override
    public UserState checkState(String id) {
        UserState us = userMapper.getState(id);
        if (us.getTime() != null && us.getTime().before(new Date())){
            updateState(id);
        }
        return userMapper.getState(id);
    }

    //用户信息
    @Override
    public Map<String, Object> userInfo(String token) {
        return JwtUtil.parseToken(token);
    }

    @Override
    public Result<?> updateUser(User user) {
//        String id = (String) userInfo(token).get("id");
        if (userMapper.updateUser(user) > 0){
            return Result.success();
        }else{
            return Result.error("更新用户信息错误");
        }
    }

    @Override
    public Result<?> newToken(String token) {
        String id = (String) userInfo(token).get("id");
        Map<String, Object> claims = new HashMap<>();
        User user = findById(id);
        claims.put("id",id);
        claims.put("name",user.getName());
        claims.put("email",user.getEmail());
        claims.put("sex",user.getSex());
        claims.put("age",user.getAge());
        claims.put("ethnic",user.getEthnic());
        claims.put("img",user.getImg());
        String newToken = JwtUtil.genToken(claims);
        return Result.success(newToken);
    }

//    @Override
//    public Result<?> updateImg(String token, String img) {
//        String id = (String) userInfo(token).get("id");
//        if (userMapper.updateImg(id,img) > 0){
//            return Result.success();
//        }else{
//            return Result.error("更新头像错误");
//        }
//    }

    /*
    * 更新用户的账号状态*/
    @Override
    public boolean updateState(String id) {
        return userMapper.updateState(id) > 0;
    }

    @Override
    public boolean silence(String id, Integer minute) {
//        System.out.println("service:----" + minute);
        return userMapper.silence(id,getFutureTimeAfterNMinutes(minute)) > 0;
    }

    @Override
    public boolean suspend(String id, Integer minute) {
        return userMapper.suspend(id,getFutureTimeAfterNMinutes(minute)) > 0;
    }

    // 用户登录
    @Override
    public Result<?> login(String id, String password) {
        User u = findById(id);
        if(u != null){
            //判断账号是否处于被封禁状态
            UserState us = checkState(id);
            if(us.getState() == 2){
                return Result.error("此账号已被封禁至" + us.getTime() + ",请等待账号解禁后再登录。");
            }
            String str = Encrypt.toMD5(password);
            if(u.getPassword().equals(str)){
                // 登录成功
                Map<String,Object> claims = new HashMap<>();
//                claims.put("type","user");
                claims.put("id",u.getId());
                claims.put("name",u.getName());
                claims.put("email",u.getEmail());
                claims.put("sex",u.getSex());
                claims.put("age",u.getAge());
                claims.put("ethnic",u.getEthnic());
                claims.put("img",u.getImg());
                String token = JwtUtil.genToken(claims);
                return Result.success(token);
            }else{
                return Result.error("密码错误");
            }
        }else{
            return Result.error("不存在的账号");
        }
    }


    //用户注册
    @Override
    public Result<?> insertUser(String id, String password, String email, String code, String name, String sex, int age, String ethnic, String img) {
        if (userMapper.findUser(id) > 0){
            return Result.error("账号已存在");
        }
        if (!validationService.checkValidation(email,code)){
            return Result.error("验证码错误或已过期");
        }
        if (img == null){
            if (sex.equals("男")){
                img = "http://localhost:9999/files/10680db6d3ab4e488b6c9117e3a32792";
            }else if (sex.equals("女")){
                img = "http://localhost:9999/files/d8516c9108e24c3393cb6718a9d0ee54";
            }else{
                return Result.error("不存在的性别");
            }
        }
        int flag1 = userMapper.insertUser(id,Encrypt.toMD5(password),email,name,sex,age,ethnic,img);
        if (flag1 > 0){
            userMapper.insertUserState(id);
        }else{
            return Result.error("注册用户失败");
        }
        return Result.success();
    }

    //找回密码
    @Override
    public Result<?> findPassword(String email,String newPsd,String code) {

//        System.out.println(flag);
        if(validationService.checkValidation(email,code)){
            if (userMapper.findPassword(email,Encrypt.toMD5(newPsd)) > 0){
                return Result.success();
            }else{
                return Result.error("数据库错误！");
            }
        }else{
            return Result.error("验证码错误或过期");
        }
    }

    //更新所有的用户状态
//    @Override
//    public void updateAllUserState() {
//        ArrayList<UserState> list = userMapper.getAllUserState();
//        for (UserState userState : list) {
//            if (userState.getState() > 0){
//
//            }
//        }
//    }

    //获取所有用户信息列表
    @Override
    public Result<?> getAllUser(String token, Integer pageNum, Integer pageSize) {
        Object id = userInfo(token).get("id");
        if (adminMapper.findAdmin(id + "") == null){
            return Result.error("无权限");
        }else{
//            return Result.success(userMapper.getAllUser());
            //创建pageBean对象
            PageBean<User> pb = new PageBean<>();
            //开启分页查询
            PageHelper.startPage(pageNum,pageSize);
            //调用mapper
            List<User> users = userMapper.getAllUser();
            for (User user : users) {
                user.setPassword("******");
                checkState(user.getId());
            }
            Page<User> p = (Page<User>) users;
            //把数据填充到PageBean对象中
            pb.setTotal(p.getTotal());
            pb.setItems(p.getResult());
            return Result.success(pb);
        }
    }
}
